<template>
  <a-card class="general-card" title="部门管理" :bordered="false">
    <div class="page-container">
      <a-row>
        <a-space>
          <a-button @click="handleQuery">刷新</a-button>
        </a-space>
      </a-row>

      <a-row class="grid-m">
        <a-col :span="8">
          <a-alert type="warning"
            >当前选择编辑： {{ selectedData.departmentName }}
            <a-button
              v-if="form.departmentId"
              type="text"
              @click="cancelSelectedData"
              >取消选择</a-button
            ></a-alert
          >
          <div class="tree-bar">
            <a-tree
              :data="deptList"
              default-expand-all
              blockNode
              @select="selectTree"
              :fieldNames="{
                key: 'departmentId',
                title: 'departmentName',
                children: 'children',
              }"
            />
          </div>
        </a-col>
        <a-col :span="12">
          <a-form
            ref="deptRef"
            :model="form"
            :rules="rules"
            :style="{ width: '600px' }"
            @submit="handleSubmit"
            
          >
            <a-form-item field="departmentName" label="部门名称" disabled>
            <a-input
              v-model="form.departmentName"
              placeholder="请输入部门名称"
            />
          </a-form-item>
            <a-form-item field="roleIds" label="选择角色">
              <a-select
                v-model="form.roleIds"
                placeholder="选择角色"
                multiple
                :max-tag-count="2"
                allow-clear
                scrollbar
              >
                <a-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="orderNum" label="排序值" disabled>
            <a-input-number
              v-model="form.orderNum"
              :style="{ width: '320px' }"
              placeholder=""
              class="input-demo"
              :min="0"
            />
          </a-form-item>
            <a-form-item>
              <a-button type="primary" html-type="submit">修改并保存</a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </div>
  </a-card>
</template>

<script setup name="Dept">
  import {
    getRoleList,
    selectDepartmentRole,
    bindDepartmentRole,
    initDepartment,
  } from '@/api/setting';
  import { Message } from '@arco-design/web-vue';

  const { proxy } = getCurrentInstance();
  const deptList = ref([]);
  const loading = ref(true);
  const roleOptions = ref([]);
  const selectedData = ref({});

  const data = reactive({
    form: {},
    addForm: {},
    queryParams: {
      departmentName: undefined,
      status: undefined,
    },
    rules: {
      // departmentName: [
      //   { required: true, message: '部门名称不能为空', trigger: 'blur' }
      // ],
      // orderNum: [{ required: true, message: '排序值不能为空', trigger: 'blur' }]
    },
  });

  const { queryParams, form, rules, addForm } = toRefs(data);

  // 树选择
  function selectTree(selectedKeys, data) {
    console.log(selectedKeys, data);
    selectDepartmentRole(selectedKeys[0]).then((res) => {
      console.log('选择部门', res);
      const selectedNode = data.selectedNodes[0];
      selectedData.value = {
        departmentName: selectedNode.departmentName,
      };
      form.value = {
        departmentId: selectedNode.departmentId,
        departmentName: selectedNode.departmentName,
        roleIds: (res.data?.result || []).map((i) => i.roleId) || [],
        orderNum: selectedNode.orderNum,
      };
    });
  }
  // 取消选择树
  function cancelSelectedData() {
    form.value = {};
    selectedData.value = {};
  }
  /** 查询部门列表 */
  function getList() {
    loading.value = true;
    initDepartment(queryParams.value).then((res) => {
      deptList.value = handleTree(res.data.result, 'departmentId');
      console.log('####', deptList.value);
      loading.value = false;
    });
  }

  function handleTree(data, id, parentId, children) {
    let config = {
      id: id || 'id',
      parentId: parentId || 'parentId',
      childrenList: children || 'children',
    };

    var childrenListMap = {};
    var nodeIds = {};
    var tree = [];

    for (let d of data) {
      let parentId = d[config.parentId];
      if (childrenListMap[parentId] == null) {
        childrenListMap[parentId] = [];
      }
      nodeIds[d[config.id]] = d;
      childrenListMap[parentId].push(d);
    }

    for (let d of data) {
      let parentId = d[config.parentId];
      if (nodeIds[parentId] == null) {
        tree.push(d);
      }
    }

    for (let t of tree) {
      adaptToChildrenList(t);
    }

    function adaptToChildrenList(o) {
      if (childrenListMap[o[config.id]] !== null) {
        o[config.childrenList] = childrenListMap[o[config.id]];
      }
      if (o[config.childrenList]) {
        for (let c of o[config.childrenList]) {
          adaptToChildrenList(c);
        }
      }
    }
    return tree;
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    getList();
  }

  function getRoles() {
    // allRoleList().then((res) => {
    //   roleOptions.value = res.data
    // })
    getRoleList({ pageNumber: 1, pageSize: 10000 }).then((res) => {
      if (res.data.success) {
        // users.value = res.data.result.records;
        // form.value = data.node;
        roleOptions.value = res.data.result.records;
        console.log('角色列表', res.data.result.records);
      }
    });
  }

  function handleSubmit({ values, errors }) {
    if (!errors) {
      if (!form.value.departmentId) {
        Message.warning('请先点击选择一个部门');
        return;
      } else {
        bindDepartmentRole(form.value).then((res) => {
          Message.success('修改成功');
          getList();
        });
      }
    }
  }

  getList();
  getRoles();
</script>
<style>
  .grid-m {
    margin: 16px 0;
  }
  .tree-bar {
    max-height: 624px;
    overflow: auto;
    margin-top: 5px;
    position: relative;
    min-height: 80px;
  }
</style>
